package com.sy.simpleegg.platform.lyybox

import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.platform.BackstagePlatform
import com.sy.simpleegg.serialport.bean.ComData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.cnbleu.serialport.SerialPort

class LyyBoxBusinessController(
    dId: String,
    portName: String,
    baudrate: SerialPort.BAUDRATE,
    stopb: SerialPort.STOPB,
    datab: SerialPort.DATAB,
    parity: SerialPort.PARITY,
    private val loginFlag: Int,
    speed: Long = 10L
) : LyyBoxBaseController(portName, baudrate, stopb, datab, parity, speed) {

    private val TAG = javaClass.simpleName

    private val platform = BackstagePlatform.LYY_BOX

    private var onDataReceivedListener: OnDataReceivedListener? = null

    private var loopNetworkJob: Job? = null

    private var loopHeartBeat = true

    private var recHeartBeat = false

    private var heartBeatInterval: Long = 10*1000L

    init {
        log("打开lyy盒子，设备ID=$dId 串口号=$portName 波特率=$baudrate 停止位=$stopb 数据位=$datab 校验位=$parity")
        loopBoxNetwork()
    }

    private fun loopBoxNetwork(){
        try {
            loopNetworkJob?.cancel()

            loopNetworkJob = MainScope().launch(Dispatchers.IO) {
                do {
                    recHeartBeat = false
                    getBoxNetwork()
                    delay(heartBeatInterval)
                    if (!recHeartBeat){
                        heartBeatInterval = 5*1000
                        onDataReceivedListener?.onHeartBeat(false)
                    }
                }while (loopHeartBeat)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("")
        }
    }

    override fun pushCheckConnect(dataHex: String) {
        log("盒子下发--查询链接状态：$dataHex")
        respCheckConnect(loginFlag)
        onDataReceivedListener?.onPushCheckConnect(dataHex)
    }

    override fun pushCloud(dataHex: String) {
        log("盒子下发--云上分（出币）：$dataHex")
        val addCodeHex = dataHex.substring(8, 10)
        val outCoinsHex = dataHex.substring(10, 14)
        val amountHex = dataHex.substring(14, 18)
        onDataReceivedListener?.onPushCloud(addCodeHex, outCoinsHex, amountHex)
    }

    override fun pushCheckState(dataHex: String) {
        log("盒子下发--查询控制板状态：$dataHex")
        onDataReceivedListener?.onPushCheckState(dataHex)
    }

    override fun pushCloudNew(dataHex: String) {
        log("盒子下发--云上分（新）：$dataHex")
        val uniqueCodeHex = dataHex.substring(10, 22)
        val amountHex = dataHex.substring(22, 26)
        val outCoinsHex = dataHex.substring(26, 30)
//        val orderEntity = makeOrder(uniqueCodeHex, amountHex, outCoinsHex)
//        orderEntity?.let{
//            onDataReceivedListener?.onPushCloudNew(orderEntity, dataHex)
//        }
        onDataReceivedListener?.onPushCloudNew(uniqueCodeHex, amountHex, outCoinsHex, dataHex)
    }

    override fun pushOutResultResp(dataHex: String) {
        log("盒子下发--响应控制板出币结果：$dataHex")
        onDataReceivedListener?.onPushOutResultResp(dataHex)
    }

    override fun pushGetTerminalConfig(dataHex: String) {
        log("盒子下发--获取终端配置：$dataHex")
        onDataReceivedListener?.onPushGetTerminalConfig(dataHex)
    }

    override fun pushSetTerminalConfig(dataHex: String) {
        log("盒子下发--设置终端配置：$dataHex")
        onDataReceivedListener?.onPushSetTerminalConfig(dataHex)
    }

    override fun pushPayQrCodeResp(dataHex: String) {
        //该⼆维码链接的地址格式为：http://m.leyaoyao.com/lyy/t/<设备号>
        log("盒子下发--标准二维码链接：$dataHex")
        onDataReceivedListener?.onPushPayQrCodeResp(dataHex)
    }

    override fun pushOutCountListResp(dataHex: String) {
        log("盒子下发--响应控制板上传账目增量：$dataHex")
        onDataReceivedListener?.onPushOutCountListResp(dataHex)
    }

    override fun pushBoxNetworkResp(dataHex: String) {
        log("盒子下发--盒子网络状态：$dataHex")
        recHeartBeat = true
        heartBeatInterval = 10*1000
        onDataReceivedListener?.onHeartBeat(true)
        onDataReceivedListener?.onPushNetworkResp(dataHex)
    }

    /**
     * 组装订单实体
     * @param uniqueCodeHex 订单号（唯一编码）
     * @param amountHex 金额（分）
     * @param coinsHex 币数
     */
//    private fun makeOrder(uniqueCodeHex: String, amountHex: String, coinsHex: String): OrderEntity?{
//        try {
//            val orderNumberByteArr = ByteUtil.hexToByteArray(uniqueCodeHex)
//            val orderNumber = String(orderNumberByteArr!!)
//            val now = Date()
//            val orderEntity = OrderEntity()
//            orderEntity.date = DateUtil.getDate(now)
//            orderEntity.time = DateUtil.getDate2(now)
//            orderEntity.onDutyCode = Constants.ONDUTY_CODE
//            orderEntity.orderNumber = orderNumber
//            orderEntity.success = 0
//            orderEntity.inCoin = 0
//            orderEntity.payType = MQConfig.FOREWARD_SCAN_PAYTYPE_TOGETHER//聚合支付
//            orderEntity.outCoin = coinsHex.toInt(16).toLong()
//            orderEntity.amount = amountHex.toInt(16).toString()
//            orderEntity.remainAmount = "0"
//            orderEntity.accountRemainCoin = 0
//            Logger.d("收到订单：" + GsonUtil.getInstance().toJson(orderEntity))
//            return orderEntity;
//        }catch (e: Exception){
//            e.printStackTrace()
//            log("组装订单实体异常：${e.message}")
//            return null
//        }
//    }

    interface OnDataReceivedListener{
        fun onPushCheckConnect(dataHex: String)
        fun onPushCloud(addCodeHex: String, coinsHex: String, amountHex: String)
        fun onPushCheckState(dataHex: String)
//        fun onPushCloudNew(orderEntity: OrderEntity, dataHex: String)
        fun onPushCloudNew(uniqueCodeHex: String, amountHex: String, coinsHex: String, dataHex: String)
        fun onPushOutResultResp(dataHex: String)
        fun onPushGetTerminalConfig(dataHex: String)
        fun onPushSetTerminalConfig(dataHex: String)
        fun onPushPayQrCodeResp(dataHex: String)
        fun onPushOutCountListResp(dataHex: String)
        fun onPushNetworkResp(dataHex: String)
        fun onHeartBeat(heartBeat: Boolean)

    }

    fun setOnDataReceivedListener(listener: OnDataReceivedListener){
        onDataReceivedListener = listener
    }

    private fun log(msg: String){
        logFile(msg)
    }

    override fun cmdTimeout(comData: ComData) {
        log("指令超时无响应")
    }
}